package com.accenture.portal.controller;


import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Array;
import java.util.List;
import java.util.Random;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.accenture.portal.model.User;
import com.accenture.portal.service.UserService;
import com.accenture.portal.util.SendValidationEmailUtil;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Controller
public class UserController {
	
	private static Logger business = Logger.getLogger(UserController.class.getName());
	
	@Autowired
	@Resource (name="userServiceImpl")
	private UserService us;
	
	
	/**
	 * 只返回aboutme页面
	 * @author qinhong.wang
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("aboutMe.action")
	public ModelAndView aboutMe (HttpServletRequest request, HttpServletResponse response, Model model) {
		return new ModelAndView ("aboutme");
	}

	/**
	 * 登出功能
	 * @author qinhong.wang
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("logout.action")
	public String logout (HttpServletRequest request, HttpServletResponse response, Model model) {
		//获取user session
		request.getSession().removeAttribute("user");
		request.getSession().invalidate();
		//遍历cookie， 并清理
		Cookie[] cookies = request.getCookies();
		for (int i = 0; i < cookies.length; i++) {
			cookies[i].setMaxAge(0);
			response.addCookie(cookies[i]);
		}
		return "login/login";
	}
	
	/**
	 * 用户头像上传，数据库存图片路径
	 * @author qinhong.wang
	 * @param name
	 * @param file
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping("upload.action")
	public String fileUpload (@RequestParam("file") MultipartFile file, HttpServletRequest request, HttpServletResponse response, Model model) {
		
		if (!file.isEmpty()) {
			
			//设置图片的路径
			String path = request.getSession().getServletContext().getRealPath("/"+"data");
			//InputStream path = request.getSession().getServletContext().getResourceAsStream("data");
			System.out.println("*******************" + path);
			
			
			//获取图片名称
			String fileName = file.getOriginalFilename();
			
			//设置图片格式为.jpg
			if (!fileName.endsWith(".jpg")) {
				return "failUpload";
			}
			
			//设置目标路径
			File targetFile = new File (path, fileName);
			
			//若没有目标文件夹则创建
			if (!targetFile.exists()) {
				targetFile.mkdirs();
			}
			
			//上传
			try {
				file.transferTo(targetFile);
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
			
			//设置url
			String url =  request.getContextPath() + "/data/" + fileName;
			System.out.println(url);
			User loggedUser = (User) request.getSession().getAttribute("user");
			loggedUser.setUser_image(url);
			
			us.uploadImg(loggedUser);
			model.addAttribute("user", loggedUser);

			return "aboutme";
		}
		return "failUpload";
	}
	
	/**
	 * 通过用户名进行模糊查询
	 * @author qinhong.wang
	 * @param name 前台获取到的name值
	 * @param response
	 * @param model
	 * @throws Exception 
	 */
	@RequestMapping("searchByname.action")
	public void searchByName (String name, HttpServletRequest request, HttpServletResponse response, Model model) throws Exception {
		//System.out.println(name);
		List<User> li = us.searchByname("%" + name + "%");
		String text = JSONArray.fromObject(li).toString();
		//System.out.println("************************" +text);
		//String text = "hello".toString();
		//request.getSession().setAttribute("nameList", li);
		PrintWriter out = response.getWriter();
		out.write(text);
		//System.out.println("-----success-----");
//		for (User user: li) {
//			System.out.println(user.getUser_name());
//		}

	}
	
	
	
	/**
	 * 显示所有用户
	 * @author kaizhe.yang
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("getAllUser.action")  
    public String getAllUser(HttpServletRequest request,Model model){  
        List<User> user = us.findAll();  
        model.addAttribute("userList", user);  
        return "allUser";  
    }  
	/**
	 * 增加用户
	 * @author kaizhe.yang
	 * @param record
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	
	@RequestMapping("registerView.action")
	public ModelAndView registerView (HttpServletRequest request, HttpServletResponse response) {
		return new ModelAndView ("register");
	}
	
	@RequestMapping(value="add.action", method=RequestMethod.POST)
	public String add (@ModelAttribute("user") User user, HttpServletRequest request, HttpServletResponse response, Model model) {

		/*if (user.getUser_levelid() == null || "".equals(user.getUser_password()) || "".equals(user.getUser_name())) {
			model.addAttribute("errorMsg", "Please enter your information!!!");
			return "register";
		} */
		

		if ("".equals(user.getUser_name())) {
			model.addAttribute("errorMsg", "Please enter your name!!!");
			return "register";
		} 
		
		
		if ("".equals(user.getUser_password()) ) {
			model.addAttribute("errorMsg", "Please enter your password!!!");
			return "register";
		} 
		
		if (user.getUser_levelid() == null ) {
			model.addAttribute("errorMsg", "Please enter your level!!!");
			return "register";
		} 
		
	if(user.getUser_levelid() > 13 || user.getUser_levelid() < 5) {
			model.addAttribute("errorMsg", "Please enter a valid employee level!!!");
			return "register";
		}
		
		us.add(user);
		
		int number = (int)request.getSession().getAttribute("count");
		return "redirect:searchByPage.action?number=" + number;
	}
	
	/**  
     * 删除用户  
     * @author kaizhe.yang
     * @param id  
     * @param request  
     * @param response  
     */  
	
	@RequestMapping("delete.action")
	public String delete (@RequestParam("id") int id ,@ModelAttribute("user") User record, HttpServletRequest request, HttpServletResponse response, Model model) {

		//System.out.println(id);
		us.delete(id);
		int number = (int)request.getSession().getAttribute("number");
		System.out.println(number);
		return "redirect:searchByPage.action?number=" + number;

	}
	
	/**  
     * 根据id查询单个用户  
     * @author kaizhe.yang
     * @param id  
     * @param request  
     * @return  
     */  
    @RequestMapping("getUser.action")  
    public String getUser(int id, HttpServletRequest request, Model model){ 
        model.addAttribute("user", us.findById(id));  
        return "editUser";  
    }  	
	
    
    /**  
     *编辑用户  
     * @author kaizhe.yang
     * @param user  
     * @param request  
     * @return  
     */  
    @RequestMapping(value="updateUser.action", method=RequestMethod.POST)  
    public String updateUser(User user,HttpServletRequest request,Model model){
		
    	us.update(user);

		model.addAttribute("registerMsg", "register success!!!");
		//return "redirect:getAllUser.action";


		int number = (int)request.getSession().getAttribute("number");
		
		//LogManagerUtil.recordBusinessLog("Alice", "user", "update", "success","update successful");
		//business.debug("success");
		
		return "redirect:searchByPage.action?number=" + number;
    }
    /**  
     *分页 
     * @author kaizhe.yang
     * @param number  
     * @param request  
     * @return  
     */  
    @RequestMapping(value="searchByPage.action")  
    public String searchByPage(@RequestParam("number") int number, HttpServletRequest request,Model model){
		
    	// 设置每页显示多少行
    	int page = 6;
    	
		//获取当前页
		if (number < 1) {
			number = 1;
		}
		
		//总条数
    	int total = us.totalCount();
    	//总页数
    	int count = total/page;
    	if (total % page != 0) {
    		count++;
    	}
    	if(count==0){
    		count=1;
    	}
    	if (number > count) {
    		number = count;
    	}
    	
    	List<User> li = us.searchByPage((number-1)*page, page);
    	
    	request.getSession().setAttribute("number", number);
    	model.addAttribute("userList", li);
    	request.getSession().setAttribute("count", count);
    	
    	return "allUser";
    }
    
    
   	@RequestMapping("management.action")
   	public ModelAndView management (HttpServletRequest request, HttpServletResponse response, Model model) {
   		return new ModelAndView ("management");
   	}
   	
   	@RequestMapping("searchUser.action")
   	public String searchUser(@RequestParam("userSearchWords") String userSearchWords1, HttpServletRequest request, HttpServletResponse response, Model model) throws Exception {
		String userSearchWords="%"+userSearchWords1+"%";
   		List<User> userListSearch = us.searchUser(userSearchWords);
		model.addAttribute("userListSearch", userListSearch);
		return "userListSearch";
	}
   	
   	/**  
     *跳转到修改密码界面
     * @author kaizhe.yang
     * @param user  
     * @param request  
     * @return  
     */  
    @RequestMapping(value="toModifyUserPassword.action")  
    public String toModifyUserPassword(HttpServletRequest request,Model model){
			return "user/modifyUserPassword";
    }
    /**  
     *检验旧密码是否正确
     * @author kaizhe.yang
     * @param user  
     * @param request  
     * @return  
     */ 
    @RequestMapping(value="modifyUserPassword.action")  
    public void modifyUserPassword(@RequestParam("oldPassword") String oldPassword,
    		@RequestParam("userName") String userName,
    		HttpServletRequest request,HttpServletResponse response,Model model){
//    	String user_name=user.getUser_name();
//    	String user_password=user.getUser_password();
//    	String user_password111="";
    	User userGet=us.modifyUserPassword(userName, oldPassword);
    	String passwordRight="";
    	String passwordWrong="";
    	String result="";
    	if(userGet!=null){
    		passwordRight="1";
    		result=passwordRight;
//    		JSONObject json = JSONObject.fromObject(passwordRight);
//    		result = json.toString();
    		
    	}
    	else{
    		passwordWrong="0";
    		result=passwordWrong;
//    		JSONObject json = JSONObject.fromObject(passwordWrong);
//    		result = json.toString();
    	}
    	
//    	JSONObject json = JSONObject.fromObject(articleChosen);
//		String result = json.toString();
		
		try {
			response.getWriter().write(result);
			response.getWriter().flush();//清空缓冲区，完成写入
		} catch (IOException e) {
			e.printStackTrace();
		}
    }
    /**  
     *保存修改密码
     * @author kaizhe.yang
     * @param user  
     * @param request  
     * @return  
     */ 
    @RequestMapping(value="modifyUserPassword.action", method=RequestMethod.POST)  
    public String modifyUserPassword(
    		@RequestParam("password") String user_password,
    			HttpServletRequest request,Model model){
    		Integer user_id=((User)request.getSession()
    			.getAttribute("user")).getUser_id();//获取当前user_id
    	User user=new User();
    	user.setUser_password(user_password);
    	user.setUser_id(user_id);
    	us.updateModifyUserPassword(user);
    	return "redirect:logout.action";
    }
    
    /**  
     *跳转至注册界面
     * @author kaizhe.yang
     * @param user  
     * @param request  
     * @return  
     */ 
    @RequestMapping(value="toUserRegister.action")  
    public String toUserRegister(HttpServletRequest request,Model model){
    	
			return "user/userRegister";
    }
    /**  
     *检验用户名是否存在
     * @author kaizhe.yang
     * @param user  
     * @param request  
     * @return  
     */ 
    @RequestMapping(value="confirmUserName.action")  
    public void confirmUserName(@RequestParam("userName") String userName,
    		HttpServletRequest request,HttpServletResponse response,Model model){
    	User userGet=us.confirmUserName(userName);
    	String userNameRight="";
    	String userNameWrong="";
    	String result="";
    	if(userGet!=null){
    		userNameRight="1";
    		result=userNameRight;
    	}
    	else{
    		userNameWrong="0";
    		result=userNameWrong;
    	}
		try {
			response.getWriter().write(result);
			response.getWriter().flush();//清空缓冲区，完成写入
		} catch (IOException e) {
			e.printStackTrace();
		}
    }
    
    /**  
	 *检验用手机号是否存在
	 * @author kaizhe.yang
	 * @param user  
	 * @param request  
	 * @return  
	 */ 
    @RequestMapping(value="confirmTel.action")  
    public void confirmTel(@RequestParam("tel") String tel,
    		HttpServletRequest request,HttpServletResponse response,Model model){
    	User userGet=us.confirmTel(tel);
    	String telRight="";
    	String telWrong="";
    	String result="";
    	if(userGet!=null){
    		telRight="1";
    		result=telRight;
    	}
    	else{
    		telWrong="0";
    		result=telWrong;
    	}
		try {
			response.getWriter().write(result);
			response.getWriter().flush();//清空缓冲区，完成写入
		} catch (IOException e) {
			e.printStackTrace();
		}
    }
    
    /**  
	 *检验用邮箱是否存在
	 * @author kaizhe.yang
	 * @param email  
	 * @param request  
	 * @return  
	 */ 
    @RequestMapping(value="confirmEmail.action")  
    public void confirmEmail(@RequestParam("email") String email,
    		HttpServletRequest request,HttpServletResponse response,Model model){
    	User userGet=us.confirmEmail(email);
    	String emailRight="";
    	String emailWrong="";
    	String result="";
    	if(userGet!=null){
    		emailRight="1";
    		result=emailRight;
    	}
    	else{
    		emailWrong="0";
    		result=emailWrong;
    	}
		try {
			response.getWriter().write(result);
			response.getWriter().flush();//清空缓冲区，完成写入
		} catch (IOException e) {
			e.printStackTrace();
		}
    }
    
    /**  
   	 *绘制验证码
   	 * @author kaizhe.yang
   	 * @param request  
   	 * @param response  
   	 * @return  
   	 */ 
    @RequestMapping("userAuthCode.action")
	public void getAuthCode(HttpServletRequest request, 
			HttpServletResponse response, HttpSession session) throws IOException {
		int width = 63;
		int height = 37;
		Random random = new Random();
		//设置response 头信息
		//禁止缓存
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		
		//生成缓冲区image类
		BufferedImage image = new BufferedImage(width, height, 1);
		//产生image类的Graphics用于绘制操作
		Graphics g = image.getGraphics();
		//Graphics类的样式
		g.setColor(this.getRandColor(200,250));
		g.setFont(new Font("Times New Roman", 0,28));
		g.fillRect(0, 0, width, height);
		//绘制干扰线
		
		for(int i = 0;i < 40;i++) {
			g.setColor(this.getRandColor(130,200));
			int x = random.nextInt(width);
			int y = random.nextInt(height);
			int x1 = random.nextInt(12);
			int y1 = random.nextInt(12);
			g.drawLine(x, y, x + x1, y + y1);
		}
		
		//绘制字符
		String strCode = "";
		for(int i =0;i < 4;i++) {
			String rand = String.valueOf(random.nextInt(10));
			strCode = strCode + rand;
			g.setColor(new Color(20 + random.nextInt(110),20 + 
					random.nextInt(110),20 + random.nextInt(110)));
			g.drawString(rand, 13*i+6, 28);
		}
		
		//将字符保存到session中的前端的验证(前台未接收到strCode)
		session.setAttribute("strCode", strCode);
		
		g.dispose();
		
		ImageIO.write(image, "JPEG", response.getOutputStream());
		response.getOutputStream().flush();
		
	}
	
	//创建生成颜色的方法
		Color getRandColor(int fc, int bc) {
			Random random = new Random();
			if(fc > 255)
				fc = 255;
			if(bc > 255)
				bc = 255;
			int r = fc + random.nextInt(bc - fc);
			int g = fc + random.nextInt(bc - fc);
			int b = fc + random.nextInt(bc - fc);
			return new Color(r,g,b);
		}	
		
		/**
		 * 验证码的验证
		 * @author kaizhe.yang
		 * @param strCode
		 * @param checkcode
		 */
		public int verifyAuthCode(String strCode, String checkcode) {
			if(checkcode == null||checkcode.equals("")) {
				return 0;//空
			} else if(!checkcode.equals(strCode)) {
				return -1;//错误
			} else {
				return 1;//正确
			}
		}
		/**
		 * 用户注册
		 * @author kaizhe.yang
		 * @param record
		 * @param request
		 * @param response
		 * @param model
		 * @return
		 * @throws Exception 
		 */
		@RequestMapping(value="userRegister.action", method=RequestMethod.POST)
		public String userRegister (@ModelAttribute("user") User user, HttpServletRequest request, HttpServletResponse response,HttpSession session, Model model) throws Exception {

			//获取页面输入的验证码
			String checkcode = (String) request.getParameter("checkCode");
			String strCode = (String) session.getAttribute("strCode");
			
			//验证码校验
			int authCodeFlag = verifyAuthCode(strCode, checkcode);
			if(authCodeFlag == -1) {
				model.addAttribute("failCheckCodeMsg", "Incorrect checkCode. Please try again.");
				return "user/userRegister";
			} 
			//保存用户信息并发送邮件
			us.register(user);
			SendValidationEmailUtil.sendValidationEmail(user.getUser_email(), user.getUser_name());
			
			 //System.out.print(user.getUser_email());
			 System.out.print(user.getUser_name());
			
			return "user/userRegister" ;
			
		}
		
		 @RequestMapping(value = "webHref.action")

		    public String webHref(@RequestParam("uName") String userName,
		    		HttpServletRequest request,
					HttpServletResponse response) {

			// String urlthere = request.getRequestURI();
			// System.out.print(urlthere);
			// String urlthere = request.getRequestURI();
	    	 System.out.print(" (╯-_-)╯╧╧ ~~!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
	    	// System.out.println(urlthere);
	    	// String userName= urlthere.split("?uName=")[1];
	    	 System.out.print(userName);
	    	 us.activationUser(userName);
		        return "redirect:loginView.action";

		    }
}
	
